<template>
  <HorizontalLayout v-if="auth === 'edit' && manualConfigs && manualConfigs.length" class="relation-wrap">
    <slot name="field" :isLink="isLink"/>
    <template #right>
      <RelationButton
          :rowId="rowId"
          :rowIndex="rowIndex"
          :context="context"
          :subFormId="subFormId"
          v-if="showRelationButton"
          :manualConfigs="manualConfigs"/>
    </template>
  </HorizontalLayout>
  <template v-else-if="auth !== 'hide'">
    <slot name="field" :isLink="isLink"/>
  </template>
</template>
<script setup>
import HorizontalLayout from '@comp/Layout/HorizontalLayout.vue';
import RelationButton from '@comp/FormEngine/field/relation/RelationButton.vue';
import {computed} from 'vue';
import {createProps} from '@/utils';
import {AuthType} from '@comp/FormEngine/Constants';

defineOptions({name: 'RelationWrap'});

const props = defineProps({
  auth: createProps(String),
  fieldConfig: createProps(String),
  subFormId: createProps(String),
  rowIndex: createProps(Number),
  rowId: createProps(String),
  context: createProps(Object, () => undefined),
});

function openRelationForm() {
  props.context.openRelationForm({
    sss: 1
  });
}

const isLink = computed(() => {
  return true
})

const isHide = computed(() => {
  return props.auth === AuthType.hide;
})

const showRelationButton = computed(() => {
  let configs = manualConfigs.value;
  return props.auth === 'edit' && configs && configs.length;
});

const manualConfigs = computed(() => {
  return getManualConfigs();
});

function getManualConfigs() {
  if (!props.context) return undefined;
  let formDefinition = props.context.formDefinition;
  if (!formDefinition) return undefined;
  let res = [], relations = formDefinition.relations || [];
  relations.forEach(r => {
    if (r.relationType === 'manual' && r.enable) {
      let index = r.manuals.findIndex(m => {
        try {
          let manualAuth = props?.context?.formModel?._manualAuth || {};
          if (!manualAuth[m.id]) return false;
        } catch (e) {
          console.log(e);
        }
        return m.manualSelectorFieldId === props.fieldConfig.id;
      });
      if (index !== -1) {
        res.push({manual: r.manuals[index], relation: r});
      }
    }
  });
  return res;
}

defineExpose({
  openRelationForm
});

</script>
<style>
.relation-wrap {
  background: white;
  align-items: center;
  justify-content: center;
  height: fit-content !important;
}
</style>